# -*- encoding: utf-8 -*-
"""
File Name: subscriber_manager
Description: Manages subscribers for different channels, allowing adding, removing, starting, and stopping of subscribers.
Author : 'lirui'
date: 11/1/2024
Contact: marjey_lee@163.com
Change Activity:
11/1/2024:
"""
import ll
from projects.monitoring.alarms_manager.services.base_subscriber import BaseSubscriber
from projects.monitoring.alarms_manager.services.subscription_info_handle import handle_subscribe_info
from projects.monitoring.common.utils.redis_keys_util import RedisKeysUtil


class SubscriberManager:
    """
    Manages a list of subscribers, allowing for adding, removing, starting, and stopping of subscribers.
    """

    def __init__(self):
        """
        Initializes the SubscriberManager with an empty list of subscribers.
        """
        self._subscribers = []

    def add_subscriber(self, channel):
        """
        Adds a subscriber to the specified channel.

        Args:
            channel (str): The channel to subscribe to.
        """

        subscriber = BaseSubscriber(channel)
        subscriber.set_recall(handle_subscribe_info)
        subscriber.subscribe()
        self._subscribers.append(subscriber)

    def create_all_subscribers(self):
        """
        Creates subscribers for all channels obtained from RedisKeysUtil.
        """
        keys = RedisKeysUtil.get_publisher_keys()
        for key in keys:
            self.add_subscriber(key)

    def remove_subscriber(self, channel):
        """
        Removes the subscriber from the specified channel.

        Args:
            channel (str): The channel to unsubscribe from.
        """
        for subscriber in self._subscribers:
            if subscriber.channel == channel:
                self._subscribers.remove(subscriber)

    def subscribe(self):
        """
        Starts all subscribers by subscribing them to their respective channels.
        """
        for subscriber in self._subscribers:
            subscriber.subscribe()

    def stop(self):
        """
        Stops all subscribers.
        """
        for subscriber in self._subscribers:
            subscriber.stop()


# Singleton instance of SubscriberManager
SUBSCRIBER_MANAGER = SubscriberManager()
